package com.lj.page;

import com.lj.dao.ParamsInfoDao;
import com.lj.dao.SqliteHelper;
import com.lj.dao.StaticData;
import com.lj.domain.ParamsInfo;
import com.lj.domain.SimpleResponse;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * Created by dave_suwei on 2017/12/7.
 */
public class ParamsGetServlet extends HttpServlet{
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding( "UTF-8" );

        SimpleResponse sr=new SimpleResponse();
        sr.setOk(true);
        sr.setMsg("成功!");
        //取参数
        ParamsInfo paramsInfo=null;
        SqliteHelper sh= (SqliteHelper) req.getAttribute("sh");
        if(sh!=null) {
            ParamsInfoDao paramsInfoDao = new ParamsInfoDao(sh);
            paramsInfo=paramsInfoDao.getParams();
        }
        //sr.setEntry(paramsInfo);

        if(paramsInfo==null){
            //sr.setOk(false);
            //sr.setMsg("!");
            paramsInfo = new ParamsInfo();
            String sd= StaticData.getStartDate();
            if(sd!=null&&!StaticData.checkAndSet()){
                    paramsInfo.setStartDate(sd);
            }else {
                //开始日期给个随机数
                String startDate = "2018-01-15";
                double rand = Math.random();
                int addDate = (int) (rand * 25);
                System.out.println("addDate->" + addDate);
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                try {
                    Date date = dateFormat.parse(startDate);
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTime(date);
                    calendar.add(Calendar.DATE, addDate);
                    startDate = dateFormat.format(calendar.getTime());
                    System.out.println("startDate->" + startDate);
                    paramsInfo.setStartDate(startDate);
                    StaticData.setStartDate(startDate);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
        }

        sr.setEntry(paramsInfo);

        System.out.println("paramsInfo->"+paramsInfo);

        resp.setContentType("application/json");
        resp.setCharacterEncoding("UTF-8");
        resp.getWriter().println(sr.toJson());
    }
}
